package com.tencent.liteav.demo.player.demo;

import android.app.ActivityManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.tencent.liteav.demo.player.R;
import com.tencent.liteav.demo.player.expand.ui.TCVodPlayerListAdapter;
import com.tencent.liteav.demo.superplayer.SubtitleSourceModel;
import com.tencent.liteav.demo.superplayer.SuperPlayerGlobalConfig;
import com.tencent.liteav.demo.superplayer.helper.IntentUtils;
import com.tencent.liteav.demo.vodcommon.entity.SuperVodListLoader;
import com.tencent.liteav.demo.vodcommon.entity.VideoListModel;
import com.tencent.liteav.demo.vodcommon.entity.VideoModel;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodConstants;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * SuperPlayer main activity.
 * <p>
 * 超级播放器主Activity
 */

public class SuperPlayerActivity extends FragmentActivity implements View.OnClickListener,
        TCVodPlayerListAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    private RelativeLayout mLayoutTitle;
    private ImageView mImageBack;
    private ImageButton mImageLink;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mVodPlayerListView;
    private SuperVodListLoader mSuperVodListLoader;
    private TCVodPlayerListAdapter mVodPlayerListAdapter;
    private List<VideoListModel> mVodList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.superplayer_activity_supervod_player);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initView();
        initData();

        updateList();
    }


    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if (getActivityCount() == 1) {
            startMainActivity();
        }
        super.finish();
    }

    private int getActivityCount() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
        return taskInfoList.size();
    }

    private void startMainActivity() {
        Intent intent = new Intent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setAction("com.tencent.liteav.action.liteavapp");
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        IntentUtils.safeStartActivity(this, intent);

    }

    private void initView() {
        mLayoutTitle = (RelativeLayout) findViewById(R.id.superplayer_rl_title);
        mImageBack = (ImageView) findViewById(R.id.superplayer_iv_back);
        mImageBack.setOnClickListener(this);
        mImageLink = (ImageButton) findViewById(R.id.superplayer_ib_webrtc_link_button);
        mImageLink.setOnClickListener(this);

        mVodPlayerListView = (RecyclerView) findViewById(R.id.superplayer_recycler_view);
        mVodPlayerListView.setLayoutManager(new LinearLayoutManager(this));
        mVodPlayerListAdapter = new TCVodPlayerListAdapter(this);
        mVodPlayerListAdapter.setOnItemClickListener(this);
        mVodPlayerListView.setAdapter(mVodPlayerListAdapter);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.superplayer_swipe_refresh_layout_list);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    private void initData() {
        mVodList = new CopyOnWriteArrayList();
        mSuperVodListLoader = new SuperVodListLoader(this);

        initSuperVodGlobalSetting();
    }

    private void addVideoModelIntoVodPlayerListAdapter(VideoModel videoModel) {
        VideoListModel videoListModel = new VideoListModel();
        videoListModel.addVideoModel(videoModel);
        mVodPlayerListAdapter.addSuperPlayerModel(videoListModel);
    }

    private List<VideoModel> getSubtitleVideoData() {
        VideoModel model = null;
        model = new VideoModel();
        model.placeholderImage = "http://1500005830.vod2.myqcloud.com/43843ec0vodtranscq1500005830/dc455d1d387702306937256938/coverBySnapshot_10_0.jpg";
        model.videoURL = "http://1500005830.vod2.myqcloud.com/43843ec0vodtranscq1500005830/dc455d1d387702306937256938/adp.10.m3u8";
        SubtitleSourceModel subtitleSourceModel = null;
        subtitleSourceModel = new SubtitleSourceModel();
        subtitleSourceModel.name = "ex-cn-srt";
        subtitleSourceModel.url = "https://mediacloud-76607.gzc.vod.tencent-cloud.com/DemoResource/TED-CN.srt";
        subtitleSourceModel.mimeType = TXVodConstants.VOD_PLAY_MIMETYPE_TEXT_SRT;
        model.subtitleSourceModelList.add(subtitleSourceModel);

        subtitleSourceModel = new SubtitleSourceModel();
        subtitleSourceModel.name = "ex-in-srt";
        subtitleSourceModel.url = "https://mediacloud-76607.gzc.vod.tencent-cloud.com/DemoResource/TED-IN.srt";
        subtitleSourceModel.mimeType = TXVodConstants.VOD_PLAY_MIMETYPE_TEXT_SRT;

        model.subtitleSourceModelList.add(subtitleSourceModel);

        subtitleSourceModel = new SubtitleSourceModel();
        subtitleSourceModel.name = "ex-en-vtt";
        subtitleSourceModel.url = "https://mediacloud-76607.gzc.vod.tencent-cloud.com/DemoResource/TED-EN.vtt";
        subtitleSourceModel.mimeType = TXVodConstants.VOD_PLAY_MIMETYPE_TEXT_VTT;
        model.subtitleSourceModelList.add(subtitleSourceModel);
        model.title = getResources().getString(R.string.super_player_multi_subtitle_video);
        List<VideoModel> list = new ArrayList<>();
        list.add(model);

        model = new VideoModel();
        model.placeholderImage = "http://1500005830.vod2.myqcloud.com/6c9a5118vodcq1500005830/3a76d6ac387702303793151471/387702307093360124.png";
        model.videoURL = "http://1500005830.vod2.myqcloud.com/6c9a5118vodcq1500005830/3a76d6ac387702303793151471/iP3rnDdxMH4A.mov";
        model.title = getResources().getString(R.string.super_player_multi_sound_track_video);
        list.add(model);

        return list;
    }

    private void updateVodList() {
        ArrayList<VideoModel> superPlayerModels = mSuperVodListLoader.loadDefaultVodList(this.getApplicationContext());
        superPlayerModels.addAll(getSubtitleVideoData());
        for (VideoModel videoModel : superPlayerModels) {
            addVideoModelIntoVodPlayerListAdapter(videoModel);
            addVideoModelIntoVodList(videoModel);
        }

        ArrayList<VideoModel> circleModels = mSuperVodListLoader.loadCircleVodList();
        final VideoListModel circleVideoListModel = new VideoListModel();
        circleVideoListModel.videoModelList = circleModels;
        circleVideoListModel.isEnableDownload = false;
        circleVideoListModel.title = getString(R.string.superplayer_carousel_list_title);
        circleVideoListModel.icon = "http://1500005830.vod2.myqcloud.com/6c9a5118vodcq1500005830/6f443f33387702302226773793/2luyOg7pOR0A.png";
        mVodPlayerListAdapter.addSuperPlayerModel(circleVideoListModel);
        mVodList.add(circleVideoListModel);

        ArrayList<VideoModel> cacheModels = mSuperVodListLoader.loadCacheVodList();
        final VideoListModel cacheVideoListModel = new VideoListModel();
        cacheVideoListModel.videoModelList = cacheModels;
        cacheVideoListModel.isEnableDownload = true;
        cacheVideoListModel.title = getString(R.string.superplayer_offline_cache_title);
        cacheVideoListModel.icon = "http://1500005830.vod2.myqcloud.com/6c9a5118vodcq1500005830/ae6444ab387702302227194724/n6SJb2ORhQMA.png";
        mVodPlayerListAdapter.addSuperPlayerModel(cacheVideoListModel);
        mVodList.add(circleVideoListModel);
    }

    private void initSuperVodGlobalSetting() {
        SuperPlayerGlobalConfig prefs = SuperPlayerGlobalConfig.getInstance();
        prefs.enableFloatWindow = true;
        SuperPlayerGlobalConfig.TXRect rect = new SuperPlayerGlobalConfig.TXRect();
        rect.x = 0;
        rect.y = 0;
        rect.width = 640;
        rect.height = (int) (640 * SuperPlayerGlobalConfig.PLAYER_VIEW_DISPLAY_RATIO);
        prefs.floatViewRect = rect;
        prefs.enableHWAcceleration = true;
        prefs.renderMode = TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
        prefs.playShiftDomain = "liteavapp.timeshift.qcloud.com";
    }

    @Override
    public void onItemClick(List<VideoModel> videoModelArrayList) {
        if (videoModelArrayList.size() == 1) {
            if (videoModelArrayList.get(0).appid > 0) {
                TXLiveBase.setAppID("" + videoModelArrayList.get(0).appid);
            }
            playVideoModel(videoModelArrayList.get(0));
        } else {
            playWithModelList(videoModelArrayList);
        }
    }

    private void playWithModelList(List<VideoModel> videoModelArrayList) {
        SuperPlayerDetailActivity.startForList(this, new ArrayList<>(videoModelArrayList));
    }

    private void playVideoModel(VideoModel videoModel) {
        SuperPlayerDetailActivity.startForModel(this, videoModel);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.superplayer_iv_back) {
            finish();
        } else if (id == R.id.superplayer_ib_webrtc_link_button) {
            showCloudLink();
        }
    }

    private void showCloudLink() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://cloud.tencent.com/document/product/454/18872"));
        IntentUtils.safeStartActivity(this, intent);
    }

    private void updateList() {
        mVodPlayerListAdapter.clear();
        if (mVodList.isEmpty()) {
            updateVodList();
        } else {
            for (VideoListModel videoListModel : mVodList) {
                mVodPlayerListAdapter.addSuperPlayerModel(videoListModel);
            }
        }
        mVodPlayerListAdapter.notifyDataSetChanged();
    }

    private void addVideoModelIntoVodList(VideoModel videoModel) {
        VideoListModel videoListModel = new VideoListModel();
        videoListModel.addVideoModel(videoModel);
        mVodList.add(videoListModel);
    }

    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
    }
}
